/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.is.city.routemanager;

import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ResourceBundle;
import javax.swing.JToggleButton;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.map.MapLayer;
import org.geotools.swing.JMapPane;
import org.geotools.swing.action.MapAction;
import org.is.ga.Solver;

/**
 *
 * @author oleg
 */
public class MultiPointGuideAction extends MapAction {
    private static final ResourceBundle stringRes = ResourceBundle.getBundle("META-INF/Text");
    public static final String TOOL_NAME = stringRes.getString("tool_name_guide");
    /** Tool tip text */
    public static final String TOOL_TIP = stringRes.getString("tool_tip_guide");
    /** Cursor */
    public static final String CURSOR_IMAGE = "/guiden.png";
    
    JToggleButton jToggleButton;
    GuideMapPaneListener gmpl;
    RoutePanel routePanel;
    String mode;

    public MultiPointGuideAction(JToggleButton jToggleButton, RoutePanel routePanel, JMapPane mapPane,String mode) {
        this.routePanel = routePanel;
        this.jToggleButton = jToggleButton;
        String toolName = "MultiPointGuideTool";
        this.mode=mode;
        super.init(mapPane, toolName, TOOL_TIP, CURSOR_IMAGE);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (this.jToggleButton.isSelected()) {
            gmpl = new GuideMapPaneListener(this, getMapPane(), jToggleButton, mode);
            getMapPane().addMouseListener(gmpl);

        } else {
            if(mode == null ? "n" == null : mode.equals("n")){
                //вынимаем точки
                addPoints(gmpl.getPoints());
            }
            getMapPane().removeMouseListener(gmpl);
        }
    }

    public void addPoints(DirectPosition2D points[]){
        routePanel.addRoute(points,AbstractRouteFactory.OrderType.NOTORDERED);
        removeTempLayers();
    }

    private void removeTempLayers() {
        MapLayer[] layers = getMapPane().getMapContext().getLayers();
        LinkedList list = new LinkedList();
        for (int i = 0; i < layers.length; i++) {
            if ( layers[i].getTitle() != null ){
                if (layers[i].getTitle().contains(new String("temp"))) {
                    list.add(i);
                }
            }
        }

        for (Iterator it = list.descendingIterator(); it.hasNext();) {
            Object next = it.next();
            getMapPane().getMapContext().removeLayer((Integer) next);
        }

    }
}
